// http_response.dart
import 'package:series_play/utils/log.dart';

class HttpResponse<T> {
  final int code;
  final String message;
  final T? data;

  HttpResponse({required this.code, required this.message, this.data});

  // factory HttpResponse.fromJson(Map<String, dynamic> json) {
  //   return HttpResponse(
  //     code: json['code'] ?? -1,
  //     message: json['message'] ?? '',
  //     data: json['data'],
  //   );
  // }

  factory HttpResponse.fromJson(
    Map<String, dynamic> json, {
    T Function(Map<String, dynamic>)? fromJson,
    T Function(List<dynamic>)? fromJsonList,
  }) {
    final rawData = json['data'];

    T? parsedData;

    if (rawData == null) {
      parsedData = null;
    } else if (rawData is List && fromJsonList != null) {
      // 处理 List<Model>
      parsedData = fromJsonList(rawData);
    } else if (rawData is Map<String, dynamic> && fromJson != null) {
      // 处理 Model
      parsedData = fromJson(rawData);
    } else {
      parsedData = rawData;
    }

    return HttpResponse(
      code: json['code'] ?? -1,
      message: json['message'] ?? '',
      data: parsedData,
    );
  }

  bool get isSuccess => code == 200;

  @override
  String toString() {
    return 'HttpResponse{code: $code, message: $message, data: $data}';
  }
}
